import type { MenuDataItem } from '@ant-design/pro-components';
import { createFCBrowserRouter, FCRouteObject } from './fc-router-dom/fc-route';
import { fcRoutes } from './routes';
import { convertTSTRoutesToURLMap, RouteUrlMap } from './utils/convert';
import { menuStore } from '@/stores';

let request: Promise<any>;

const initialLoader = () => {
  if (request) {
    return request;
  }

  return (request = Promise.resolve().then(() => {
    const loop = (tstRoutes?: FCRouteObject[]) => {
      const menus = [];

      let childrenCache = [];

      tstRoutes?.forEach((tstRoute: FCRouteObject) => {
        let menuChildren;

        if (tstRoute?.children) {
          menuChildren = loop(tstRoute?.children);
          childrenCache = childrenCache.concat(menuChildren);
        }

        let menu: MenuDataItem = {};

        if (tstRoute?.menu) {
          const { name, icon } = tstRoute?.menu;

          menu = {
            children: menuChildren || [{}],
            icon,
            name,
            key: tstRoute?.key,
            path: tstRoute?.path,
            label: name,
            hideInMenu: !!tstRoute?.hideInMenu,
          };

          if (tstRoute?.checkPermission) {
            menu.hideInMenu = menu.hideInMenu || !tstRoute?.checkPermission();
          }

          menus.push(menu);
        }

        if (tstRoute?.checkPermission && tstRoute?.lazy) {
          if (tstRoute?.checkPermission()) {
            tstRoute?.lazy();
          }
        }
      });

      return menus?.length > 0 ? menus : childrenCache;
    };
    const menus = loop(fcRoutes);

    menuStore.setMenus(menus);

    return [];
  }));
};
const router = createFCBrowserRouter(fcRoutes, { initialLoader });

export const routeUrlMap: RouteUrlMap = convertTSTRoutesToURLMap(fcRoutes);

export default router;
